package campus.aiit.ssl.manage.modbus.provider.misc;

import campus.aiit.ssl.manage.modbus.provider.misc.ByteUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

@Slf4j
public class SocketPush {

  public String pushMessage(String ip, int port, String message) {
    /* Socket建立连接 */
    Socket socket = new Socket();
    try {
      SocketAddress socketAddress = new InetSocketAddress(ip, port);
      socket.connect(socketAddress, 2000); // 连不上的?毫秒断掉连接
    } catch (IOException e) {
      e.printStackTrace();
      log.error("连接失败");
      return "连接失败";
    }
    /* 发布消息 */
    boolean waitIssue = true;
    if (message.startsWith("00")) { // 为广播（地址码为00）发布，无应答
      waitIssue = false;
    }
    String result = "";
    StringBuffer buffer = new StringBuffer();
    try {
      byte[] bstream = ByteUtils.hexStringToBytes(message);
      OutputStream os = socket.getOutputStream();
      os.write(bstream);
      socket.setSoTimeout(2000); // 设置socket读超时时间?毫秒
      if (waitIssue) { // 是否等待返回结果
        // 装饰流BufferedReader封装输入流（接收客户端的流）
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        DataInputStream dis = new DataInputStream(bis);
        byte[] bytes = new byte[1]; // 一次读取一个byte
        boolean t = true;
        while (t) {
          dis.read(bytes);
          buffer.append(ByteUtils.toHexString(bytes));
          if (message.toUpperCase().equals(buffer.toString().toUpperCase())) {
            t = false;
          }
        }
        result = "发送成功，返回内容：" + buffer.toString();
      }
      return result;
    } catch (IOException e) {
      result = buffer.toString();
      if (!result.equals("") && result != null) {
        return "发送成功，返回内容：" + result;
      } else {
        return "发送失败";
      }
    }
  }
}